<template>
  <div class="header-box">
    <header class="header">
      <div class="left">
        <img
          @click="toHome"
          class="guet-logo c-p"
          src="@/assets/images/guet-logo.png"
          alt="guet-logo"
        />
        <section class="left">{{ currentTime }}</section>
      </div>
      <section class="right">
        <el-tooltip effect="dark" content="联系管理员" placement="bottom">
          <img
            class="contact-admin m-r-20 c-p"
            src="@/assets/images/contact_admin.png"
            alt="联系管理员"
            @click="doContact"
          />
        </el-tooltip>
        <el-tooltip v-if="noticeStore.hasNotice" effect="dark" content="通知" placement="bottom">
          <img
            @click="onReadMessage"
            class="message-notice m-r-20 c-p"
            src="@/assets/images/message-has.png"
            alt="消息通知"
          />
        </el-tooltip>
        <el-tooltip v-else effect="dark" content="通知" placement="bottom">
          <img
            @click="onReadMessage"
            class="message-notice m-r-20 c-p"
            src="@/assets/images/message-none.png"
            alt="消息通知"
          />
        </el-tooltip>
        <div v-if="!userStore.userInfo?.isLogin" class="flex">
          <section @click="toLogin" class="c-p">登录</section>
          <section @click="toRegister" class="register c-p">注册</section>
        </div>
        <div v-else class="flex">
          <div class="user-info flex m-r-20">
            <img
              v-if="userStore.userInfo?.userMsg?.avatar"
              :src="userStore.userInfo.userMsg.avatar"
              alt="用户头像"
            />
            <img v-else src="@/assets/images/default-avatar.png" alt="用户头像" />
            <span class="m-l-10">{{ userStore.userInfo?.userMsg?.nickName }}</span>
          </div>
          <section @click="toLogout" class="c-p">退出登录</section>
        </div>
      </section>
    </header>
  </div>
  <chatDialog ref="chatDialogRef" :user="user" />
  <div class="platform-logo" style="height: 120px;">
    <img class="platform-logo-img m-t-20" src="@/assets/images/guet-main.png" style="width: 100%;height: 100%;" />
    <!-- <div class="search">
      <el-input v-model="inputValue" placeholder="请输入关键词" :prefix-icon="Search" clearable />
    </div> -->
  </div>
  <el-drawer v-model="isDrawerShow">
    <template #header>
      <h2>消息通知</h2>
      <el-tooltip effect="dark" content="删除消息通知" placement="bottom">
        <img
          class="c-p"
          @click="onDeleteNotice"
          style="width: 30px"
          src="@/assets/images/delete.png"
          alt="删除"
        />
      </el-tooltip>
    </template>
    <template #default>
      <div class="notice-list">
        <template v-for="(notice, index) in noticeStore.noticeList" :key="index">
          <div v-if="notice.cmd === SIGNAL_TYPE_ONE_TO_ONE" class="chat-message">
            <h3>{{ `${notice.remoteName}给您发来了一条消息` }}</h3>
            <el-link @click="onCheckMsg" type="primary">点击查看</el-link>
          </div>
          <div v-if="notice.cmd === SIGNAL_TYPE_SYSTEM" class="system-push">
            <div v-if="notice.msg.type === 1" class="achievement">
              <h3>系统给您推荐了成果</h3>
              <el-link
                v-for="item in notice.msg.ids"
                @click="onCheckAchievement(item.id)"
                type="primary"
                >{{ item.title }}</el-link
              >
            </div>
            <div v-else class="demand">
              <h3>系统给您推荐了需求</h3>
              <el-link
                v-for="item in notice.msg.ids"
                @click="onCheckDemand(item.id)"
                type="primary"
                >{{ item.title }}</el-link
              >
            </div>
          </div>
        </template>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
// import { Search } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import type { DateTimeFormatOptions } from 'intl';
import { useUserStore } from '@/store/user';
import { logout } from '@/api/login';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useNoticeStore } from '@/store/nitice';
import { SIGNAL_TYPE_ONE_TO_ONE, SIGNAL_TYPE_SYSTEM } from '@/constants/constants';
import { getIsLogin, getLoginUserId } from '@/utils/storage';
import chatDialog from '@/components/chat-dialog/index.vue';
import { reqUserInfo } from '@/api/system';

// const inputValue = ref<string>('');
const router = useRouter();
const userStore = useUserStore();

const noticeStore = useNoticeStore();
function onReadMessage() {
  const isLogin = getIsLogin();
  if (!isLogin) {
    ElMessage({
      message: '登录后才能查看消息通知',
      type: 'warning',
    });
    return;
  }
  isDrawerShow.value = !isDrawerShow.value;
  noticeStore.setHasNotice(false);
}

// 删除消息通知列表的回调
function onDeleteNotice() {
  ElMessageBox.confirm('确定清空消息通知吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    noticeStore.noticeList = [];
  });
}
// 点击查看消息
function onCheckMsg() {
  isDrawerShow.value = false;
  router.push({
    name: 'chat',
  });
}
// 点击查看推荐的成果
function onCheckAchievement(id: string) {
  isDrawerShow.value = false;
  router.push({
    name: 'achievementDetail',
    query: {
      aId: id,
    },
  });
}
// 点击查看推荐的需求
function onCheckDemand(id: string) {
  isDrawerShow.value = false;
  router.push({
    name: 'needDetail',
    query: {
      nId: id,
    },
  });
}

const toLogin = () => {
  router.push({
    name: 'login',
  });
};
const toRegister = () => {
  router.push({
    name: 'register',
  });
};
const toLogout = () => {
  ElMessageBox.confirm('确定退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      logout().then((res: any) => {
        if (res.code === 200) {
          // 退出后清空部分值
          userStore.logout();
          // 退出登录后重新加载页面，防止出现用户已退出但能访问需要授权的页面
          window.location.hash = '/login';
          // window.location.reload();
        }
      });
    })
    .catch(() => {});
};
const toHome = () => {
  router.push({
    name: 'home',
  });
};
const isDrawerShow = ref<boolean>(false);

// 显示时间
const currentTime = ref<string>('');
onMounted(() => {
  // 初始化时间
  updateTime();
  // 计算距离下一次需要更新时间的毫秒数
  const now = new Date();
  const nextDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, 0);
  const timeToNextUpdate = nextDay.getTime() - now.getTime();
  // 延迟执行更新时间的函数
  setTimeout(() => {
    updateTime();
    setInterval(updateTime, 24 * 60 * 60 * 1000); // 每隔一天更新一次时间
  }, timeToNextUpdate);
});
function updateTime() {
  const now = new Date();
  const options: DateTimeFormatOptions = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    weekday: 'long',
  };
  currentTime.value = now.toLocaleString('zh-CN', options);
}

const user = ref<any>({});

// 联系管理员
const chatDialogRef = ref<InstanceType<typeof chatDialog> | null>(null);
async function doContact() {
  const isLogin = getIsLogin();
  if (!isLogin) {
    ElMessage({
      message: '登录后才能联系管理员',
      type: 'warning',
    });
    return;
  }
  // 获取系统管理员信息
  const adminId = 1;
  const res: any = await reqUserInfo(adminId);
  if (res.code === 200) {
    user.value = res.data;
    if (user.value.userId === getLoginUserId()) {
      ElMessage({
        message: '不能将消息发给自己！',
        type: 'error',
      });
      return;
    }
    if (chatDialogRef.value) {
      chatDialogRef.value.dialogFormVisible = true;
    }
  }
}
</script>

<style scoped lang="scss">
.header-box {
  position: relative;
  height: 50px;
  z-index: 99;
  .header {
    height: 50px;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    .left {
      .guet-logo {
        height: 45px;
      }
    }
    .right {
      color: #3265e3;
      .register {
        margin-left: 5px;
      }
      .message-notice,
      .contact-admin {
        height: 30px;
      }
      .user-info {
        img {
          height: 30px;
          border-radius: 5px;
        }
      }
    }
    .left,
    .right {
      display: flex;
      align-items: center;
      padding: 0 20px;
    }
  }
}
.platform-logo {
  position: relative;
  height: 300px;
  overflow: hidden;
  &-img {
    width: 100%;
    min-width: 1000px;
    object-fit:cover;
    object-position: top;
  }
  // .search {
  //   width: 300px;
  //   position: absolute;
  //   top: 100px;
  //   right: 250px;
  // }
}
.notice-list {
  .chat-message {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .system-push,
  .chat-message {
    padding: 5px;
    border-top: 1px solid #a2a5a8;
  }
  .system-push {
    .achievement,
    .demand {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
  }
}
</style>
